package com.wwt.server.config.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * 权限控制
 * 判断用户是否具有访问该URL所需要权限
 */
@Configuration

public class CustomUrlDecisionManager  implements AccessDecisionManager {
    @Override
    //用户的角色在authen里(封装的之前传到安全上下文的用户信息） 资源需要的角色在collection里
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute: collection) {
            String needRole = configAttribute.getAttribute();
            if ("ROLE_LOGIN".equals(needRole)){
                //如果为匿名用户  即未登录
                if (authentication instanceof AnonymousAuthenticationToken)
                    throw new AccessDeniedException("未登录，请登录！");
                return;
            }
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority grantedAuthority: authorities) {
                if (grantedAuthority.getAuthority().equals(needRole))
                    return;
            }
        }
        throw new AccessDeniedException("权限不足！");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
